package com.example.fashionshoes.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.example.fashionshoes.constant.JwtConst;
import com.example.fashionshoes.exception.*;
import com.example.fashionshoes.pojo.dto.UserDTO;
import com.example.fashionshoes.pojo.dto.UserPasswordDTO;
import com.example.fashionshoes.pojo.po.Result;
import com.example.fashionshoes.pojo.po.User;
import com.example.fashionshoes.pojo.vo.UserLoginVo;
import com.example.fashionshoes.pojo.vo.UserVo;
import com.example.fashionshoes.service.UserService;
import com.example.fashionshoes.utils.AliOssUtil;
import com.example.fashionshoes.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@Slf4j
@Validated
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private AliOssUtil aliOssUtil;
    /**
     * 用户登录
     *
     * @param user 用户账户密码
     * @return 用户信息（不包含密码）
     */
    @PostMapping("/login")
    public Result<UserLoginVo> toLogin(@Validated(User.Login.class) @RequestBody User user) {
        UserLoginVo userLoginVo;
        try {
            userLoginVo = userService.toLogin(user);
        } catch (UserNotFoundException e) {
            return Result.error("账户不存在");
        } catch (PasswordIncorrectException e) {
            return Result.error("密码错误");
        } catch (BusinessException e){
            return Result.error("该账户已被禁用，请联系管理员");
        } catch (Exception e) {
            log.info("错误信息" + LocalDateTime.now() + " " + e.getMessage());
            return Result.error("系统错误，请稍后重试");
        }

        return Result.success(userLoginVo);
    }

    /**
     * 用户注册
     *
     * @param user 用户填写的数据
     * @return 用户信息
     */
    @PostMapping("/register")
    public Result<UserLoginVo> toRegister(@Validated(User.Register.class)@RequestBody User user) {
        UserLoginVo userLoginVo;
        try {
            userLoginVo = userService.toRegister(user);
        } catch (PasswordNotMatchException e) {
            return Result.error("前后密码不一致");
        } catch (UsernameExistException e) {
            return Result.error("用户名已存在");
        }
        return Result.success(userLoginVo);
    }
    /**
     * 修改密码
     * @param userPasswordDTO 要修改的密码
     * @return null
     */
    @PostMapping("/changePassword")
    public Result<Object> changePassword(@Validated @RequestBody UserPasswordDTO userPasswordDTO){
        try {
            userService.changePassword(userPasswordDTO);
        } catch (PasswordNotMatchException e) {
            return Result.error("前后密码不一致");
        } catch (PasswordIncorrectException e) {
            return Result.error("密码错误");
        } catch (SamePasswordException e) {
            return Result.error("新旧密码一致");
        }
        return Result.success();
    }

    /**
     * 修改用户信息
     * @param userDTO 用户信息
     * @return 修改后的用户信息
     */
    @PostMapping("/modify")
    public Result<UserVo> modifyUserInfo(@RequestBody @Validated UserDTO userDTO){
        UserVo userVo = userService.modifyUserInfo(userDTO);
        return Result.success(userVo);
    }
    @GetMapping("/info")
    public Result<UserVo> getUserInfo(){
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get(JwtConst.USER_ID);
        User user = userService.getById(userId);
        UserVo userVo = BeanUtil.copyProperties(user, UserVo.class);
        return Result.success(userVo);
    }
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        String uploadURL;
        String originalFilename = file.getOriginalFilename();
        String extendName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName  = UUID.randomUUID() + extendName;
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get(JwtConst.USER_ID);
        try {
            uploadURL = aliOssUtil.upload(file.getBytes(), fileName);
            //修改用户头像至数据库
            userService.lambdaUpdate().eq(User::getId,userId).set(User::getAvatar,uploadURL).update();
            return Result.success(uploadURL);
        } catch (IOException e) {
            log.info("文件上传失败{}",file);
        }
        return Result.error("文件上传失败！");
    }
}
